package cn.b504.qpcr.controller;

import cn.b504.qpcr.entity.AjaxResult;
import cn.b504.qpcr.entity.save.SaveData;
import cn.b504.qpcr.entity.save.SaveExcelData;
import cn.b504.qpcr.interfaces.Excel;
import cn.b504.qpcr.utils.FileUtils;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.WebApplicationContext;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@RestController
@RequestMapping("downloadAction")
@Scope(value = WebApplicationContext.SCOPE_SESSION)
public class SaveController {
  private final Excel excel;  // service
  private SaveData data = null;
  private SaveExcelData excelData = null;

  public SaveController(Excel excel) {
    this.excel = excel;
  }

  @PostMapping("downloadAll") //  先发这个请求存储数据
  public void data_saveFile(@RequestBody SaveData data) {
    this.data = data;
  }

  @GetMapping("downloadAllUrl") //  再发这个请求开启下载流
  public void data_saveFileUrl(HttpServletResponse response) {
    if (this.data == null) {
      return;
    }
    String fileName = data.getUserName() + "-" + data.getExperimentName();
    if (fileName.equals("-")) {
      FileUtils.outputFileWithDate(response, data.getData(), "", ".cqa");
      return;
    }
    if (fileName.startsWith("-")) {
      fileName = fileName.substring(1);
    }
    if (fileName.endsWith("-")) {
      fileName = fileName.substring(0, fileName.length() - 1);
    }
    FileUtils.outputFile(response, data.getData(), fileName, ".cqa");
    this.data = null;
  }


  @PostMapping("downloadExcel") //  先发这个请求存储数据
  public void excelData_saveFile(@RequestBody SaveExcelData excelData) {
    this.excelData = excelData;
  }

  @GetMapping("downloadExcelUrl") //  再发这个请求开启下载流
  public void excelData_saveFileUrl(HttpServletResponse response) {
    if (this.excelData == null) {
      return;
    }
    String fileName = this.excelData.getUserName() + "-" + this.excelData.getExperimentName();
    if (fileName.equals("-")) {
      FileUtils.outputExcelWithDate(response, excel.generate(this.excelData.getSheets()), "");
      this.excelData = null;
      return;
    }
    if (fileName.startsWith("-")) {
      fileName = fileName.substring(1);
    }
    if (fileName.endsWith("-")) {
      fileName = fileName.substring(0, fileName.length() - 1);
    }
    FileUtils.outputExcel(response, excel.generate(this.excelData.getSheets()), fileName);
    this.excelData = null;
  }

  @RequestMapping("downloadPath") //  保存cqa文件到指定目录
  public void path_saveFile(@RequestBody SaveData data) {
    String userName = data.getUserName();
    String experimentName = data.getExperimentName();
    if (userName.length() == 0) {
      if (experimentName.length() == 0) {
        FileUtils.outputFileWithDate(data.getData(), "public" + File.separator + "public", ".cqa", true);
      } else {
        FileUtils.outputFile(data.getData(), "public", experimentName, ".cqa", true);
      }
    } else {
      if (experimentName.length() == 0) {
        FileUtils.outputFileWithDate(data.getData(), userName, ".cqa", true);
      } else {
        FileUtils.outputFile(data.getData(), userName, experimentName, ".cqa", true);
      }
    }
  }

  @GetMapping("readPreferences")
  public AjaxResult readPreferences() throws IOException {
    String property = System.getProperty("user.home");
    String path = String.join(File.separator,System.getProperty("user.home"), "AppData\\Local\\Google\\Chrome\\User Data\\Default\\Preferences");
    Path path1 = Paths.get(path);
    byte[] data = Files.readAllBytes(path1);
    String result = new String(data, "utf-8");
    JSONObject json = JSONObject.fromObject(result);
    json.put("download","{'prompt_for_download': true}");
    File file = new File(path);
    StringBuilder jsonStr = new StringBuilder().append(json);
    file.createNewFile();
    try (BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)))) {
      bw.write(jsonStr.toString());
      return AjaxResult.ok("写入成功");
    } catch(Exception e) {
      e.printStackTrace();
      return AjaxResult.error("写入失败");
    }
  }
}

